import Vue from "vue";
import atlas from "@/atlas";
import CONFIG from "@/assets/raw/config.js";

// 定义作为前端数据存储的方法
const Store = {
    // 公共数据池
    // 每次重新进入页面清空
    storeData: {
        allConfigs: CONFIG, // 全部配置项
        isSeekSkip: null, //  是否跳过片头片尾
        bimsData: null,
        rejectManualFocus: false, // 阻止手动落焦,
        entryPage: {},
        desktopInfo: null,
        desktopStoreInfo: null, // 缓存的桌面数据
        topBarStoreInfo: null, // 缓存的topBar数据
        dongtaiTopicsErrorStoreInfo: null, // 动态主题错误，缓存的兜底数据
        flowsStoreInfo: null, // 缓存的flows数据
        topicsStoreInfo: null, // 缓存的topics数据
        flowsList: [],
        topicsList: [],
        videoSmallIndex: null,
        topicScrollTopValue: 0, // 21号组件topic距离顶部高度
        getTopicUpdateEnd: false, // 是否请求完成
        playerInfoData: null, // 当前播放的小窗视频
        routeFocusInfo: null, // 当前需要恢复的焦点信息,仅用于页面跳转
        saveFocusInfo: null, // 当前需要恢复的焦点信息,仅用于页面内缓存焦点
        childLockInfo: null, // 家长中心设置参数
        collectState: null, // 详情页当前节目收藏状态
        projectionScreenBodyInfo: null, // 投屏拉起信息
        quickChildInfo: null, // 家长中心自定义时长控制缓存
        dailyMaxMinutesInfo: null,
        isJoinBlack: false, // 节目集是否被加入黑名单
        selectSpeedIndex: 2, // 当前选中的倍速，默认1.0
        isScreenProjectionStatus: false, // 当前是否投屏状态
        switchFlowId: "", // 切换版本或切换标准版flow的switchFlowId
        versionSwitchingInfo: null, // 版本切换的内容
        deskConfig: {}, // 自定义桌面属性
        indexHistroyBoxIndex: -1, // 记住21号组件观看记录的位置
        parentCountTime: 0, // 休息倒计时
    },
    // 临时数据
    // 当某些特定接口请求失败时， 会将临时数据，补充到正式数据中
    tempStoreData: {},
};

const WK_WATCH = "WK_AroundLife";

const localKeys = [
    "quickChildInfo",
    "dailyMaxMinutesInfo",
    "parentCountTime",
    "myScore"
];

const EventObj = {};

const GLOBAL_EVENTS = ["video"];

let ROUTE_NAME = "";

Store.init = function (callback) {
    console.log("Store.init:start");
    Vue.Native.callNative("ConsoleModule", "log", "Store.init:start");
    Vue.Native.callNative("AtlasModule", "dataGet", WK_WATCH, (v) => {
        Vue.Native.callNative(
            "ConsoleModule",
            "log",
            `Store.init:dataGet:${v}`
        );
        console.log(`Store.init:dataGet:${v}`);
        if (v) {
            const storeInfo = JSON.parse(v);
            Vue.Native.callNative(
                "ConsoleModule",
                "log",
                `Store.init:dataGet:storeInfo${v}`
            );
            console.log(`Store.init:dataGet:storeInfo${v}`);
            for (const iterator of localKeys) {
                this.storeData[iterator] = storeInfo[iterator];
            }
            callback && callback();
        } else {
            let newLocalKeys = [];
            for (const iterator of localKeys) {
                newLocalKeys.push(`${WK_WATCH}_${iterator}`);
            }
            atlas
                .multiGet(newLocalKeys)
                .then((v1) => {
                    const { data = [] } = v1;
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            const tempData = data[i];
                            if (tempData && tempData.length > 0) {
                                if (tempData[1]) {
                                    try {
                                        const keyArr = tempData[0].split(
                                            `${WK_WATCH}_`
                                        );
                                        if (keyArr.length === 2) {
                                            this.setData(
                                                keyArr[1],
                                                JSON.parse(tempData[1])
                                            );
                                            console.log(
                                                `Store.init:multiGet:keyArr[1]${
                                                    keyArr[1]
                                                };${typeof tempData[1]}`
                                            );
                                            Vue.Native.callNative(
                                                "ConsoleModule",
                                                "log",
                                                `Store.init:multiGet:keyArr[1]${
                                                    tempData[0]
                                                };${typeof tempData[1]}`
                                            );
                                        }
                                    } catch (e) {
                                        console.log(
                                            `Store.init:multiGet:error:${tempData[0]}`
                                        );
                                    }
                                }
                            }
                        }
                    }
                })
                .finally(() => {
                    Vue.Native.callNative(
                        "ConsoleModule",
                        "log",
                        "Store.init:finally"
                    );
                    callback && callback();
                });
        }
        // callback && callback();
    });
};

// Store.setConfig = function(json){
//     const _obj = Object.assign({}, Store.getData("allConfigs"), json);
//     this.setData("allConfigs", _obj, true)
// }

Store.setData = function (key, value, save) {
    this.storeData[key] = value;
    if (save) {
        this.saveMsData();
        if (localKeys.includes(key)) {
            console.log("localStorage:key", key);
            localStorage.setItem(`${WK_WATCH}_${key}`, JSON.stringify(value));
        }
    }
};

Store.localStorageSetItem = function (key, value) {
    atlas
        .multiSet([[`${WK_WATCH}_${key}`, JSON.stringify(value)]])
        .then((v) => {
            console.log("localStorageSetItem:multiSet", v);
        });
};

Store.localStorageGetItem = async function (key) {
    let result = null;
    try {
        const res = await atlas.multiGet([`${WK_WATCH}_${key}`]);
        const { data = [] } = res;
        console.log("localStorageGetItem:multiGet", data.length);
        if (data.length > 0) {
            try {
                const tempData = data[0];
                result = JSON.parse(tempData[1]);
            } catch (e) {
                console.log(`localStorageGetItem:multiGet:erro ${e}`);
            }
        }
        return result;
    } catch (error) {
        return result;
    }
};

// 批量存硬盘
Store.setAllKeysData = function (arr) {
    console.log("setAllKeysData:getAllKeysData:multiSet:arr", arr);
    atlas.multiSet(arr).then((v2) => {
        console.log("setAllKeysData:getAllKeysData:multiSet", v2);
    });
};

// 批量取硬盘
Store.getAllKeysData = async function (keys) {
    console.log("getAllKeysData:getAllData", keys);
    if (keys.length === 0) return [];
    let resultArr = Array(keys.length).join(".").split(".");
    try {
        const res = await atlas.multiGet(keys);
        const { data = [] } = res;
        console.log("getAllKeysData:multiGet", data.length);
        if (data.length > 0) {
            for (var i = 0; i < data.length; i++) {
                const tempData = data[i];
                if (tempData && tempData.length > 0) {
                    if (tempData[1]) {
                        try {
                            resultArr[i] = JSON.parse(tempData[1]);
                        } catch (e) {
                            console.log(
                                `getAllKeysData:multiGet:catch ${tempData[0]} error`
                            );
                        }
                    }
                }
            }
        }
        console.log("getAllKeysData:multiGet:resultArr", resultArr);
        return resultArr;
    } catch (error) {
        console.log("getAllKeysData:error", error);
        return resultArr;
    }
};

Store.getData = function (key) {
    return this.storeData[key];
};

Store.getMsData = function (callback) {
    Vue.Native.callNative("AtlasModule", "dataGet", WK_WATCH, (v) => {
        callback && callback(v);
    });
};

// 保存MS缓存数据
Store.saveMsData = function () {
    let saveInfo = {};
    for (let index = 0; index < localKeys.length; index++) {
        const element = localKeys[index];
        saveInfo[element] = this.storeData[element];
    }
    Vue.Native.callNative("AtlasModule", "dataSet", {
        key: WK_WATCH,
        val: JSON.stringify(saveInfo),
    });
};

Store.setRouteName = function (routeName) {
    ROUTE_NAME = routeName;
};

Store.on = function (name, fun) {
    let _name = `${ROUTE_NAME}.${name}`;
    if (GLOBAL_EVENTS.includes(name)) {
        _name = name;
    }
    EventObj[_name] = fun;
};

Store.emit = function (name, params) {
    let _name = `${ROUTE_NAME}.${name}`;
    if (GLOBAL_EVENTS.includes(name)) {
        _name = name;
    }
    for (let key in EventObj) {
        if (key === _name || key.indexOf(`${_name}.`) > -1) {
            EventObj[key](params);
        }
    }
};

// 获取本地数据
// Store.getLocalData = function() {
//     return new Promise(resolve => {
//         Vue.Native.callNative('AtlasModule', 'dataGet', WK_WATCH, v => {
//             if ( v ) {
//                 this.storeData = JSON.parse(v);
//                 resolve();
//             } else {
//                 atlas.multiGet(localKeys).then(v1 => {
//                     const { data=[]} = v1;
//                     if (data.length > 0) {
//                         for (var i=0; i< data.length; i++) {
//                             const tempData = data[i];
//                             if (tempData && tempData.length > 0) {
//                                 this.setData(tempData[0], tempData[1], 1)
//                             }
//                         }
//                     }
//                 })
//                 .finally(()=>{
//                     resolve();
//                 })
//             }
//         })
//     })
// }

// Store.setData("allConfigs", {a:1}, true);
// Store.setData("newAssortment", {b:1}, true);
// Store.setData("channelList", {c:1}, true);
// Store.init();

export default Store;
